package com.webreport.dao.hibernate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.webreport.dao.ReportDao;
import com.webreport.exception.DaoException;
import com.webreport.model.QueryModel;
import com.webreport.model.ReportModel;
import com.webreport.model.db.Report;
import com.webreport.model.db.ReportMonitor;
import com.webreport.utils.DaoUtils;
@Repository
public class ReportDaoHibernate extends GenericDaoHibernate<Report,String> implements ReportDao{

	public ReportDaoHibernate() {
		super(Report.class);
	}	
	public long queryListCount(ReportModel queryparams) throws DaoException{
		QueryModel query = this.queryListSql(queryparams);
		List list = DaoUtils.queryHQL(getHibernateTemplate(), query.getSqlCount(), query.getParams());
		if (list != null && list.size() ==1){
			return (Long)list.get(0);
		}
		return 0;
		//DaoUtils.query
	}
	public List<ReportModel> queryList(ReportModel queryparams,int startrow,int size) throws DaoException{
		List<ReportModel> results = new ArrayList<ReportModel>();
		QueryModel query = this.queryListSql(queryparams);
		List<Object[]> list = DaoUtils.queryHQL(this.getHibernateTemplate(), query.getSql(), query.getParams(), startrow, size);
		for(Object[] o:list){
			ReportModel m = new ReportModel();
			m.setReportid((String)o[0]);
			m.setReportname((String)o[1]);
			m.setAccessurl((String)o[2]);
			m.setMenuid((String)o[3]);
			m.setType((String)o[4]);
			m.setTypename((String)o[5]);
			m.setProjectname((String)o[6]);
			m.setItowner((String)o[7]);
			m.setBussinessowner((String)o[8]);
			m.setDescription((String)o[9]);
			m.setPurpose((String)o[10]);
			m.setTotalcount((Long)o[11]);
			results.add(m);
		}
		return results;
	}
	
	private QueryModel queryListSql(ReportModel queryparams){
		QueryModel query = new QueryModel();
		query.appendSelect("select reportid,reportname,accessurl,menuid,type,typename,projectname,itowner,bussinessowner,description,purpose,");
		query.appendSelect("(select count(*) from ").append(ReportMonitor.class.getName()).append(" m where m.reportid = r.reportid) as totalcount ");
		query.appendTables(Report.class.getName()).append(" r ");
				
		Map<String,Object> map = new HashMap<String,Object>();
		query.appendWhere("enabled =:enabled");
		query.addParam("enabled", true);
		if (queryparams != null){
			if (!StringUtils.isEmpty(queryparams.getMenuid())){
				query.appendWhere("menuid =:menuid");
				query.addParam("menuid", queryparams.getMenuid());
			}
			
		}
		return query;
	}
}
